#!/usr/bin/python
# -*- coding: gb2312 -*-

import SocketServer, time
import os, time, sys, thread
from socket import *

myHost = ""
myPort = 51769

BUFSZ = 5120

def now():
    return time.ctime(time.time())

class myhand(SocketServer.BaseRequestHandler):
    """
    properties: request, client_address, server
                (sockobj)                (ThreadingTCPServer)
    """
    
    def handle(self):
        sf = self.request.makefile('r')
        while 1:
            oneline = sf.readline().strip()
            print oneline
            try:
                cmd, filename = oneline.split(' ',1)
            except:
                break
            if cmd == 's':
                try:
                    dropfile = os.path.split(filename)[1]
                    fo = open(dropfile, 'wb')
                    sz = 0
                    while 1:
                        data = sf.read(BUFSZ)
                        if not data: break
                        fo.write(data)
                        sz += len(data)
                    fo.close()
                    print 'server got file: %s  size: %d'%(filename,sz)
                except:
                    print "error: can't write to file: %s"%filename
                    break
            elif cmd == 'r':
                try:
                    dropfile = os.path.split(filename)[1]
                    fo = open(dropfile, 'rb')
                    sz = 0
                    while 1:
                        data = fo.read(BUFSZ)
                        if not data: break
                        sent = self.request.send(data)
                        assert sent == len(data)
                        sz += len(data)
                    fo.close()
                    print 'server sent file: %s  size: %d'%(filename,sz)
                except:
                    print "error: can't read file: %s"%filename
            break
        self.request.close()

def sendfile(host, filename):
    sockobj = socket(AF_INET, SOCK_STREAM)
    sockobj.connect((host, myPort))
    sockobj.send('s %s\n'%filename)  # 's' command to store file
    fi = open(filename, 'rb')
    sz = 0
    while 1:
        data = fi.read(BUFSZ)
        if not data: break
        sent = sockobj.send(data)
        assert sent == len(data)
        sz += sent
    fi.close()
    sockobj.close()
    print '%s stored to server %s    %s'%(filename, host, sz)

def readfile(host, filename):
    sockobj = socket(AF_INET, SOCK_STREAM)
    sockobj.connect((host, myPort))
    sockobj.send('r %s\n'%filename)  # 's' command to store file
    fi = open(filename, 'wb')
    sz = 0
    while 1:
        data = sockobj.recv(BUFSZ)
        if not data: break
        fi.write(data)
        sz += len(data)
    fi.close()
    sockobj.close()
    print 'read file %s from server %s    %s'%(filename, host,sz)

def err_use():
    print 'usage: %s [-c filetosend host -[r|s]]'
    sys.exit(1)

if __name__ == '__main__':
    if len(sys.argv)<=1:
        sev = SocketServer.ThreadingTCPServer((myHost,myPort), myhand)
        sev.serve_forever()
        sys.exit(0)
    if sys.argv[1] == '-c':
        filename = sys.argv[2]
        host = sys.argv[3]
        if sys.argv[4] =='-r':
            readfile(host, filename)
        elif sys.argv[4] =='-s':
            sendfile(host, filename)
        else:
            err_use()
